package network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server implements Runnable {

	private String id = "Anonymous Server";
	private int port = 8000;
	private Socket socketClient;

	private static String count;
	
	public Server() {
		
	}
	
	public Server(int port) {
		this.port = port;  
	}
	
	public Server(String id) {
		this.id = id;
	}
	
	public Server(String id, Socket socketClient) {
		this.id = id;
		this.socketClient = socketClient;
	}
	
	public Server(String id, int port) {
		this.id = id;
		this.port = port;
	}
	
	@Override
	public void run() {
		try {
//			ServerSocket socketS = new ServerSocket(port);
//			System.out.println(id + " is listening to clients");
//			socketClient = socketS.accept();
//			String idS = "Anonymous Server " + count;
//			System.out.println("CLIENT : " + socketClient.getLocalPort());
//			Thread t = new Thread(new Server(idS));
//			t.start();
			
			BufferedReader bufR = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
			String read;
			while ((read = bufR.readLine()) != "END") {
				System.out.println(read);
			}
			
			BufferedWriter bufW = new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));
			bufW.write(id + " is about to close the connection !!");
			bufW.write("END");
			bufW.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		while (true) {
			ServerSocket socketS;
			try {
				socketS = new ServerSocket(8000);
				System.out.println("Server is listening to clients");
				Socket socketClient = socketS.accept();
				String idS = "Anonymous Server " + count;
				Server server = new Server(idS, socketClient);
				System.out.println("CLIENT : " + socketClient.getLocalPort());
				Thread t = new Thread(server);
				t.start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
